#include "zip.h"
#include <stdio.h>
//#include "defComm.h"
#define TRACE_LOG printf

unsigned char* do_zip(unsigned char * mem, int size, int &compressLen)
{
	int dst_len = LZ4_compressBound(size);
	unsigned char* dst = (unsigned char*) malloc(dst_len);

	if (dst == NULL)
	{
		// "can not allocate memory"
		return NULL;
	}

	memset(dst, 0, dst_len);

	// printf("size %d dst_len %d \n", size, (int)dst_len);

	// int real_len = 0;

	int ret = LZ4_compress((char*) mem, (char*) dst, size);

	// printf("ret %d \n", ret);

	if (ret <= 0)
	{
		// "can not compress"
		free(dst);
		return NULL;
	}

	compressLen = ret;
	return dst;
}

unsigned char* do_unzip(unsigned char * mem, int size, int uncompressLen)
{
	int compr_len = size;

	unsigned char* buf = (unsigned char*) malloc(uncompressLen);

	if (buf == NULL)
	{
		// "can not allocate memory"
		TRACE_LOG("do_unzip malloc is null");
		return NULL;
	}

	memset(buf, 0, uncompressLen);
	int uncompr_len = uncompressLen;

	/* unzip text section */
	int ret = LZ4_decompress_safe((char*) mem, (char*) buf, compr_len,
									uncompr_len);

	if (ret != uncompr_len)
	{
		TRACE_LOG("do_unzip len: %d, actual:%d", uncompr_len, ret);
		// "can not unzip text section"
		free(buf);
		return NULL;
	}

	return buf;
}
